import { storeBindingsBehavior } from "mobx-miniprogram-bindings";
import router from "@src/router";
import base from "@src/store/base";
import location from "@src/store/location";

Component({
  properties: {
    specList: {
      type: Array,
      value: [],
    },
    skuList: {
      type: Array,
      value: [],
    },
    categoryList: {
      type: Array,
      value: () => [],
    },
    selectSkuId: {
      type: Number,
      default: 0,
    },
    selectCategoryId: {
      type: Number,
      default: 0,
    },
    selectPlanId: {
      type: Number,
      default: 0,
    },
    cover: {
      type: String,
      default: "",
    },
  },
  behaviors: [storeBindingsBehavior, router.routerBehavior],
  storeBindings: [
    {
      store: base,
      fields: ["themeColor", "themeTitleColor", "perms"],
    },
    {
      store: location,
      fields: ["latitude", "longitude"],
      actions: ["getLocation"],
    },
  ],
  /**
   * 组件生命周期
   */
  lifetimes: {
    // 生命周期函数，可以为函数，或一个在methods段中定义的方法名
    created: function (val) {},
    attached: function (val) {},
    ready: function (val) {},
    moved: function () {},
    detached: function () {},
  },
  observers: {
    specList: function () {
      wx.nextTick(() => {
        this.initSpecList();
      });
    },
    selectSpec: function () {
      wx.nextTick(() => {
        this.computedSelectSpecDisable();
      });
    },
    selectCategoryId: function () {
      wx.nextTick(() => {
        this.initCategory();
      });
    },
    selectPlanId: function () {
      wx.nextTick(() => {
        this.initCategory();
      });
    },
    selectSkuId: function () {
      wx.nextTick(() => {
        this.initSkuPrice();
      });
    },
  },
  data: {
    newSpecList: [],
    selectSpec: [0, 0, 0, 0, 0, 0],
    skuId: 0,
    categoryId: 0,
    planId: 0,
    imgUrl: "",
    price: 0,
    stockNum: 0,
    skuPrice: 0,
    btnSpecDisable: false,
  },
  methods: {
    //初始化商品价格
    initSkuPrice() {
      console.log("初始化商品价格");
      const { skuList, newSpecList } = JSON.parse(JSON.stringify(this.data));
      const categoryInfo = this.data.categoryList.filter(
        (v) => v.id === this.data.categoryId
      )[0];
      if (this.data.selectSkuId > 0) {
        const skuInfo = skuList.filter(
          (v) => v.skuId === this.data.selectSkuId
        )[0];
        const totalPay = skuInfo?.price + (categoryInfo?.price || 0);
        //console.log("ready skuInfo", skuInfo);
        this.setData({
          selectSpec: skuInfo?.specAttrs,
          imgUrl: skuInfo?.imgUrl,
          price: (totalPay / 100).toFixed(2),
          skuPrice: skuInfo?.price / 100,
          stockNum: skuInfo?.stockNum,
        });
        // if (newSpecList.length === 3) {
        //   this.setMoreThenDisableGood();
        // } else {
        //   this.setTwoDisableGood();
        // }
        switch (newSpecList.length) {
          case 1:
            this.setOneDisableGood();
            break;
          case 2:
            this.setTwoDisableGood();
            break;
          case 3:
            this.setMoreThenDisableGood();
            break;
        }
      }
    },
    //----资源选择 开始 ----
    //点击资源
    handleSelectCategory(e) {
      const {
        currentTarget: {
          dataset: { selectitem },
        },
      } = e;
      this.setData({
        categoryId: selectitem.id,
        planId: selectitem.planId,
        price: (selectitem?.price / 100 + this.data.skuPrice).toFixed(2),
      });
      this.triggerEvent("selectCategory", selectitem);
    },
    initCategory() {
      if (
        this.data.selectCategoryId !== null &&
        this.data.selectCategoryId !== undefined
      ) {
        const { selectCategoryId, selectPlanId } = JSON.parse(
          JSON.stringify(this.data)
        );
        this.setData({
          categoryId: selectCategoryId,
          planId: selectPlanId,
        });
      }
    },
    //----资源选择 结束 ----
    //----商品选择 开始 ----
    //初始化spec选择
    initSpecList() {
      const { specList } = JSON.parse(JSON.stringify(this.data));
      specList.forEach((v) => {
        v.attrList.map((attr) => {
          attr.disable = false;
        });
      });
      this.setData({
        newSpecList: specList,
      });
    },
    //选择商品
    onTapSelectGood(e) {
      const {
        currentTarget: {
          dataset: { good, specindex },
        },
      } = e;
      //console.log("选择商品", good);
      const { selectSpec, newSpecList } = JSON.parse(JSON.stringify(this.data));
      //选择商品
      if (selectSpec[specindex] === good.id) {
        selectSpec[specindex] = 0;
      } else {
        //不可选择
        if (good.disable) return;
        selectSpec[specindex] = good.id;
      }
      this.setData({
        selectSpec,
      });
      //不可选设置
      //console.log("newSpecList.length", newSpecList.length === 2);

      switch (newSpecList.length) {
        case 1:
          this.setOneDisableGood();
          break;
        case 2:
          this.setTwoDisableGood();
          break;
        case 3:
          this.setMoreThenDisableGood();
          break;
      }
    },
    //单维度不可选设置
    setOneDisableGood() {
      console.log("单维度不可选设置");
      const { skuList, newSpecList, selectSpec } = JSON.parse(
          JSON.stringify(this.data)
      );
      let disableOption = [];
      skuList
          .filter((v) => v.status === 0)
          .forEach((sku) => {
            sku.specAttrs.forEach((spec) => {
              // console.log("不可选设置", sku, spec, selectSpecItem);
              if (spec) {
                disableOption.push(spec);
              }
            });
          });
      // //console.log('不可选设置22',disableOption)
      newSpecList.map((newSpec) => {
        newSpec.attrList.map((attr, attrIndex) => {
          attr.disable = false;
          // //console.log('不可选设置3',attr,disableOption)
          attr.disable = disableOption.includes(attr.id);
        });
      });
      this.setData({
        newSpecList,
      });
      //获取对应的sku
      this.handleSelectGoods();
    },
    //二维度不可选设置
    setTwoDisableGood() {
      console.log("二维度不可选设置");
      const { skuList, newSpecList, selectSpec } = JSON.parse(
        JSON.stringify(this.data)
      );
      let disableOption = [];
      selectSpec.forEach((selectSpecItem, selectSpecIndex) => {
        if (selectSpecItem) {
          const skus = skuList.filter(
            (v) =>
              v.specAttrs.includes(selectSpecItem) &&
              v.specAttrs[selectSpecIndex] === selectSpecItem
          );
          // console.log(
          //   "不可选设置 setTwoDisableGood",
          //   skus,
          //   selectSpec,
          //   selectSpecItem
          // );
          skus
            .filter((v) => v.status === 0)
            .forEach((sku) => {
              sku.specAttrs.forEach((spec) => {
                // console.log("不可选设置", sku, spec, selectSpecItem);
                if (spec !== selectSpecItem) {
                  disableOption.push(spec);
                }
              });
            });
          // //console.log('不可选设置22',disableOption)
          newSpecList.map((newSpec) => {
            newSpec.attrList.map((attr, attrIndex) => {
              attr.disable = false;
              // //console.log('不可选设置3',attr,disableOption)
              attr.disable = disableOption.includes(attr.id);
            });
          });
        }
      });
      this.setData({
        newSpecList,
      });
      //获取对应的sku
      this.handleSelectGoods();
    },
    //多维度不可选设置
    setMoreThenDisableGood() {
      console.log("多维度不可选设置");
      //此时是大于两维规格的
      const { selectSpec, newSpecList, skuList } = JSON.parse(
        JSON.stringify(this.data)
      );
      let newSelectSpec = [];
      let newSelectSpecStr = "";
      selectSpec.forEach((v) => {
        if (v) {
          newSelectSpec.push(v);
        }
      });
      newSelectSpecStr = newSelectSpec.join(",");
      if (newSelectSpec.length === 1) {
        //console.log("选一个的时候");
        newSpecList.map((newSpec) => {
          newSpec.attrList.map((attr, attrIndex) => {
            attr.disable = false;
          });
        });
        this.setData({
          newSpecList,
        });
      } else if (newSelectSpec.length === 0) {
        newSpecList.map((newSpec) => {
          newSpec.attrList.map((attr, attrIndex) => {
            attr.disable = false;
          });
        });
        this.setData({
          newSpecList,
        });
      } else if (newSelectSpec.length === 2) {
        //此时是未选最后一种的时候，开始禁用
        let handleSkus = [];
        let disableOption = [];
        handleSkus = skuList.filter(
          (sku) =>
            sku.specAttrs.includes(newSelectSpec[0]) &&
            sku.specAttrs.includes(newSelectSpec[1])
        );
        handleSkus
          .filter((v) => v.status === 0)
          .forEach((v) => {
            // //console.log('不可选设置',v)
            v.specAttrs.forEach((spec) => {
              if (!newSelectSpecStr.includes(spec)) {
                disableOption.push(spec);
              }
            });
          });
        newSpecList.map((newSpec) => {
          newSpec.attrList.map((attr, attrIndex) => {
            attr.disable = false;
            // //console.log('不可选设置3',attr,disableOption)
            attr.disable = disableOption.includes(attr.id);
          });
        });
        this.setData({
          newSpecList,
        });
        //console.log("sku", handleSkus, disableOption);
      } else if (newSelectSpec.length === 3) {
        //此时是未选最后一种的时候，开始禁用
        let handleSkus = [];
        let disableOption = [];
        let tmep1 = skuList.filter(
          (sku) =>
            sku.specAttrs.includes(newSelectSpec[0]) &&
            sku.specAttrs.includes(newSelectSpec[1])
        );
        let tmep2 = skuList.filter(
          (sku) =>
            sku.specAttrs.includes(newSelectSpec[1]) &&
            sku.specAttrs.includes(newSelectSpec[2])
        );
        let tmep3 = skuList.filter(
          (sku) =>
            sku.specAttrs.includes(newSelectSpec[0]) &&
            sku.specAttrs.includes(newSelectSpec[2])
        );
        handleSkus = [...tmep1, ...tmep2, ...tmep3];
        handleSkus
          .filter((v) => v.status === 0)
          .forEach((v) => {
            // //console.log('不可选设置',v)
            v.specAttrs.forEach((spec) => {
              if (!newSelectSpecStr.includes(spec)) {
                disableOption.push(spec);
              }
            });
          });
        //console.log("disableOption", disableOption);
        newSpecList.map((newSpec) => {
          newSpec.attrList.map((attr, attrIndex) => {
            attr.disable = false;
            // //console.log('不可选设置3',attr,disableOption)
            attr.disable = disableOption.includes(attr.id);
          });
        });
        this.setData({
          newSpecList,
        });
        //console.log("sku", handleSkus, disableOption);
      }
      //获取对应的sku
      this.handleSelectGoods();
      //当选择了两个的时候
      //console.log("选择了", selectSpec, newSelectSpec, newSelectSpecStr);
    },
    //获取对应的sku
    handleSelectGoods() {
      const { skuList, selectSpec, categoryList, specList } = JSON.parse(
        JSON.stringify(this.data)
      );
      const categoryInfo = categoryList.filter(
        (v) => v.id === this.data.categoryId
      )[0];
      let selectSku = null;
      let spec = [];
      let specTitle = [];
      specList.forEach((specItem, specIndex) => {
        specItem.attrList.forEach((attr) => {
          if (selectSpec.includes(attr.id)) {
            spec[specIndex] = attr;
            specTitle[specIndex] = attr.title;
          }
        });
      });
      skuList.forEach((skuItem) => {
        if (
          skuItem.specAttrs[0] === selectSpec[0] &&
          skuItem.specAttrs[1] === selectSpec[1] &&
          skuItem.specAttrs[2] === selectSpec[2] &&
          skuItem.specAttrs[3] === selectSpec[3] &&
          skuItem.specAttrs[4] === selectSpec[4] &&
          skuItem.specAttrs[5] === selectSpec[5]
        ) {
          selectSku = skuItem;
        }
      });
      if (selectSku) {
        this.setData({
          specTitle,
          skuId: selectSku.skuId,
          imgUrl: selectSku?.imgUrl ? selectSku?.imgUrl : this.data.cover,
          price: (((categoryInfo?.price || 0) + selectSku.price) / 100).toFixed(
            2
          ),
          skuPrice: selectSku.price / 100,
          stockNum: selectSku.stockNum,
        });
        // this.triggerEvent("select", {
        //   skuId: selectSku.skuId,
        //   specTitle: this.data.specTitle.join(","),
        // });
      }
      console.log("选择了", selectSku, categoryInfo, this.data);
    },

    //----商品选择 结束 ----
    //----底部按钮 开始----
    handleSubmitSelectGoods() {
      const { selectSpec, specList } = JSON.parse(JSON.stringify(this.data));
      let spec = selectSpec.filter((v) => !!v);
      if (spec.length !== specList.length) return;
      if (this.data.skuId !== null && this.data.skuId !== undefined) {
        this.triggerEvent("select", {
          skuId: this.data.skuId,
          specTitle: this.data?.specTitle?.join(","),
        });
      }
    },
    handleShowSelectGood() {
      this.triggerEvent("close");
    },
    computedSelectSpecDisable() {
      const { selectSpec, specList } = JSON.parse(JSON.stringify(this.data));
      let spec = selectSpec.filter((v) => !!v);
      this.setData({
        btnSpecDisable: spec.length !== specList.length,
      });
      return spec.length !== specList.length;
    },
    //----底部按钮 结束----
  },
});
